

package com.maoshi.shop.user.platform.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maoshi.shop.bean.model.User;
import com.maoshi.shop.bean.model.UserExtension;
import com.maoshi.shop.dao.UserMapper;
import com.maoshi.shop.service.UserExtensionService;
import com.maoshi.shop.user.comment.dto.LevelDetailDto;
import com.maoshi.shop.user.comment.service.UserLevelService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

//0 0 0/1 * * ?
@Slf4j
@Component("scoreTask")
@AllArgsConstructor
public class ScoreTask {

    private final UserMapper userMapper;
    private final UserExtensionService userExtensionService;
    private final UserLevelService levelService;

    /**
     * 将会员设为已过期状态
     */
    public void vipUserClear() {
        log.info("将会员设为已过期状态》》》》》》》》》》》》》》》》》》》》》");
        List<User> users = userMapper.selectMemberByEndTime(DateUtil.endOfDay(DateUtil.yesterday()));
        List<String> userIds = new ArrayList<>();
        users.forEach(user -> userIds.add(user.getUserId()));
        List<UserExtension> userExtensions = userExtensionService.list(new LambdaQueryWrapper<UserExtension>().in(UserExtension::getUserId, userIds));
        List<LevelDetailDto> userLevels = levelService.selectLevelAndRights(0);
        List<User> updateUsers = new ArrayList<>();
        //通过用户积分获取当前等级和下一等级
        for (UserExtension userExtension : userExtensions) {
            userExtension.setLevelType(0);
            User user = new User();
            user.setUserId(userExtension.getUserId());
            user.setLevelType(0);
            for (LevelDetailDto userLevel : userLevels) {
                if (userExtension.getGrowth() >= userLevel.getNeedGrowth()) {
                    userExtension.setLevel(userLevel.getLevel());
                    user.setLevel(userLevel.getLevel());
                }
            }
            updateUsers.add(user);
        }
        userExtensionService.updateMemberByTime(updateUsers,userExtensions);
        log.info("将会员设为已过期状态》》》》》》》》》》》》》》》》》》》》》");
    }

}
